package com.yenlien.traceyun.control.controller;

import com.alibaba.fastjson.JSONObject;
import com.yenlien.traceyun.control.controller.form.ModelCropForm;
import com.yenlien.traceyun.control.dao.*;
import com.yenlien.traceyun.control.entity.Birth;
import com.yenlien.traceyun.control.entity.Crop;
import com.yenlien.traceyun.control.entity.ModelCategory;
import com.yenlien.traceyun.control.entity.ModelCrop;
import com.yenlien.traceyun.control.service.CropService;
import com.yenlien.traceyun.control.service.ModelCropService;
import com.yenlien.traceyun.webase.controller.BaseController;
import com.yenlien.traceyun.webase.utils.CheckParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by LiuSha on 2020/3/24.
 * 模型库产物
 */
@RestController
@RequestMapping(value = "/model/crop")
public class ModelCropController extends BaseController {
    @Autowired
    private ModelCropService modelCropService;
    @Autowired
    private CropService cropService;
    @Autowired
    private CropDao cropDao;

    @Autowired
    private BirthDao birthDao;

    @Autowired
    private ModelCropDao modelCropDao;

    @Autowired
    private CompanyCropDao companyCropDao;

    @Autowired
    private ModelCategoryDao modelCategoryDao;

    /**
     * 作物查询
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Object search(@RequestBody JSONObject param) {
        return success(modelCropService.search(param.getString("categoryId"), param.getString("companyId"), param.getString("name")));
    }

    /**
     * 根据二级分类加载所有基源
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/category/{id}")
    public Object getByCategoryId(@PathVariable("id") String id) {
        return success(modelCropService.getByCategoryId(id));
    }

    /**
     * 根据二级分类查询所有基源
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/getBycategory/{id}")
    public Object getCropByCategoryId(@PathVariable("id") String id) {
        return success(modelCropService.findByCategoryId(id));
    }

    /**
     * 企业显示上级政管勾选的基源（如果上级没勾选则不显示），如果上级直接是超管则显示所有  替代上面的 /category/{id}  loadbind不需要改
     *
     * @param categoryId
     * @return
     */
    @GetMapping(value = "/getParentBind/{categoryId}")
    public Object getParentBind(@PathVariable("categoryId") String categoryId) {
        return success(modelCropService.getParentBind(categoryId));
    }


    /**
     * 添加修改
     *
     * @param from
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Object add(ModelCropForm from, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        String companyId = request.getParameter("companyId");
        if (!StringUtils.isEmpty(companyId)) {
            from.getModelCrop().setCompanyId(companyId);
        }
        return success(modelCropService.save(from, files));
    }

    /**
     * 删除作物
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public Object delete(@PathVariable("id") String id) {
        modelCropService.delecrop(id);
        return success("ok");
    }

    /**
     * 加载详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/load/{id}", method = RequestMethod.GET)
    public Object load(@PathVariable("id") String id) {
        ModelCrop modelCrop = modelCropDao.findById(id);
        List<Birth> births = birthDao.findByModelId(id);
        List<Crop> crops = cropDao.findByModelId(id);
        JSONObject result = new JSONObject();
        result.put("modelCrop", modelCrop);
        result.put("births", births);
        result.put("crops", crops);
        List<String> parentIds = modelCropService.getCategoryTree(modelCrop);
        result.put("parentIds", parentIds);
        if (parentIds != null && parentIds.size() > 0) {
            List<ModelCategory> categories = modelCategoryDao.findByIdIn(parentIds);
            result.put("parentName", categories.stream().map(p -> p.getName()).collect(Collectors.toList()));
        }
        return result;
    }

    /**
     * 绑定作物    政管和企业选择基源
     *
     * @param params
     * @return
     */
    @RequestMapping(value = "/bindone", method = RequestMethod.POST)
    public Object bindone(@RequestBody JSONObject params) {
        CheckParams.checkJson(params, new String[]{"companyId", "modelCropId", "bind", "appId"});
        String binded = params.getString("bind");
        modelCropService.bindone(params.getString("companyId"), params.getString("modelCropId"), params.getString("appId"), params.getString("bind"));
        return success("ok");
    }

    /**
     * 根据公司加载作物
     *
     * @param param
     * @return
     */
    @RequestMapping(value = "/loadbind", method = RequestMethod.POST)
    public Object findByCompany(@RequestBody JSONObject param) {
        CheckParams.checkJson(param, new String[]{"appId", "companyId"});
        return success(modelCropService.loadBinded(param.getString("companyId"), param.getString("appId")));
    }

    /**
     * 加载产出物
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/load/model/{id}")
    public Object loadCropByModelCropId(@PathVariable("id") String id) {
        return modelCropService.loadCrop(id);
    }

    /**
     * 添加产出物
     *
     * @param params
     * @return
     */
    @PostMapping(value = "/add/crop")
    public Object addCrop(@RequestBody JSONObject params) {
        CheckParams.checkJson(params, new String[]{"modelId", "position", "name", "img"});
        return modelCropService.addCrop(params.toJavaObject(Crop.class));
    }

    /*******8888888888888888888888888888888888888******/

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public Object save(ModelCrop modelCrop, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
        modelCropService.save(modelCrop, files);
        return success("success");
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Object update(ModelCrop modelCrop, HttpServletRequest request) throws Exception {
        List<MultipartFile> files = new ArrayList<>();
        if (!StringUtils.isEmpty(((MultipartHttpServletRequest) request).getFile("files"))) {
            files = ((MultipartHttpServletRequest) request).getFiles("files");
        }
//        modelCropService.update(modelCrop, files);
        return success("success");
    }

    @RequestMapping(value = "/findById/{id}", method = RequestMethod.GET)
    public Object findById(@PathVariable("id") String id) {
        return success(modelCropService.findById(id));
    }

    @RequestMapping(value = "/findByOneId/{id}", method = RequestMethod.GET)
    public Object findByOneId(@PathVariable String id) {
        return success(modelCropService.findByOneId(id));
    }

    @RequestMapping(value = "/findByTwoId/{id}", method = RequestMethod.GET)
    public Object findByTwoId(@PathVariable String id) {
        return success(modelCropService.findByTwoId(id));
    }


    @RequestMapping(value = "/company/save", method = RequestMethod.POST)
    public Object saveCompanyModel(@RequestBody JSONObject param) {
        CheckParams.checkJson(param, new String[]{"appId", "modelId", "companyId"});
        modelCropService.saveCompanyModel(param);
        return success("success");
    }

    @RequestMapping(value = "/company/delete", method = RequestMethod.POST)
    public Object deleteCompanyModel(@RequestBody JSONObject param) {
        CheckParams.checkJson(param, new String[]{"modelId", "companyId"});
        modelCropService.deleteCompanyModel(param.getString("modelId"), param.getString("companyId"));
        return success("success");
    }


    @RequestMapping(value = "/findByModelId/{modelId}", method = RequestMethod.GET)
    public Object findByModelId(@PathVariable String modelId) {
        return success(cropService.findByModelId(modelId));
    }


}
